package com.karrim.server;

import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.karrim.server.factory.SocketConnectionEventFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author andrea.cantafio
 */
public class Greeter extends Thread {

    @Inject
    @AssistedInject
    public Greeter(@Assisted ServerSocket socket, SocketConnectionEventFactory eventFactory, SocketConnectionEventDispatcher dispatcher) {
        this.socket = socket;
        this.eventFactory = eventFactory;
        this.dispatcher = dispatcher;
        start();
    }

    @Override
    public void interrupt() {
        interrupted = true;
        super.interrupt();
    }

    @Override
    public void run() {
        System.out.println("Listening on " + socket.getLocalSocketAddress());
        while (!interrupted) {
            try {
                dispatcher.dispatch(eventFactory.create(socket.accept()));
            } catch (IOException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    private SocketConnectionEventFactory eventFactory;
    private boolean interrupted = false;
    private ServerSocket socket;
    private SocketConnectionEventDispatcher dispatcher;
}
